<template>
    <div>
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1 v-text="$t('pro.public.header.Campaigns')"></h1>
            </div>
        </div>
        <div class="content container-fluid">
            <div class="portlet">
                <div class="tools flex-between">
                    <div class="tools-l grid">
                        <a-select defaultValue="All" style="min-width: 128px;">
                            <a-select-option value="All" @click="handleSelectAll">{{$t('pro.admin.All')}}</a-select-option>
                            <a-select-option value="Active" @click="handleSelectActive(ACTIVE)">
                                {{$t('pro.campaigns.active')}}
                            </a-select-option>
                            <a-select-option value="Not Active" @click="handleSelectActive(NOTACTIVE)">
                                {{$t('pro.campaigns.notActive')}}
                            </a-select-option>
                            <a-select-option value="Archived" @click="handleSelectActive(ARCHIVED)">
                                {{$t('pro.campaigns.archived')}}
                            </a-select-option>
                        </a-select>
                        <router-link to="/bidder/editcampaign">
                            <a-button type="primary" icon="plus">{{ $t('pro.campaigns.addCampaign') }}</a-button>
                        </router-link>
                        <a-input-search :placeholder="$t('pro.campaigns.searchPlaceholder')" @search="onSearch"/>
                    </div>
                    <div class="tools-r grid-r" v-if="this.$store.getters.usIsAdmin">
                        <!--<router-link to="/admin/EditSupplysettings"
                                     v-text="$t('pro.campaigns.EditSupplysettings')"></router-link>-->
                        <!--<span v-text="$t('pro.campaigns.UserMarkupRate')"></span>
                        <a-input-number
                                :defaultValue="100"
                                :min="0"
                                :max="100"
                                :formatter="value => `${value}%`"
                                :parser="value => value.replace('%', '')"
                                @change="onChange"
                        />
                        <a-button type="primary" v-text="$t('pro.campaigns.UpdateMarkup')"></a-button>-->
                        <a-button style="float: right;" type="primary" shape="circle" icon="setting" @click="onOpenChange" v-show="campaignsStatus !== ARCHIVED"/>
                    </div>
                </div>

                <div class="setting-group grid" v-if="openSetting">
                    <div class="setting-group-wrapper">
                        <a-checkbox-group
                                class="grid checkbox-grid"
                                :defaultValue="plainOptions"
                                @change="checkedChange"
                        ><a-checkbox v-for="(item,index) in plainShadow" :value="index" :key="index">
                            {{item.title}}
                        </a-checkbox>
                        </a-checkbox-group>
                        <a-button type="primary" :disabled="columnsNoChange" @click="saveCheckbox"
                                  v-text="$t('pro.public.buttonSave')"></a-button>
                    </div>
                </div>

                <div class="table">
                    <!-- <a-spin :spinning="loading"> -->
                        <div v-show="empty">
                            <a-empty image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
                                <span slot="description">{{$t('pro.campaigns.activeNotMess')}}</span>
                            </a-empty>
                        </div>

                        <div v-show="!empty">
                            <a-table
                                    :pagination="false"
                                    :columns="columns"
                                    :loading="loading"
                                    rowKey="id"
                                    @change="handleTableChange"
                                    :dataSource="data"
                                    :scroll="{x: '1200px'}"
                            >
                                <template slot="status" slot-scope="text, record">
                                    <a-switch
                                            :checked="record.status === ACTIVE ?true:false"
                                            @change="statusChange(record)"
                                            :defaultChecked="record.status === NOTACTIVE ?false:true"
                                            :disabled="(record.creativeLimit?record.creativeLimit:0)<=0 ||record.status === ARCHIVED"
                                            checkedChildren="ON"
                                            unCheckedChildren="OFF"
                                    />
                                </template>
                                <template slot="details" slot-scope="text, record">
                                    <a style="display: inline-block;width: 65px;margin: 0 auto;" href="javascript:;">
                                        {{handleDetails(record)}}
                                    </a>
                                </template>
                                <template
                                        slot="name"
                                        slot-scope="text, record"
                                >
                                    <a style="width: 150px;
                                           margin: 0 auto;
                                           overflow:hidden;
                                           white-space:nowrap;
                                           text-overflow:ellipsis;
                                           display: block"
                                       @click="handleEditCampaign(record)"
                                    >
                                        {{record.name}}
                                    </a>
                                </template>
                                <a slot="creative" slot-scope="text, record" href="javascript:;" style="display: flex;min-width: 95px">
                                <span style="margin: 0 auto">
                                    <a-button
                                            type="primary"
                                            @click="viewcreative(record)"
                                    >{{record.creativeLimit?record.creativeLimit:0}}
                                    </a-button>
                                    <a-button v-if="record.status !== ARCHIVED" type="primary" icon="plus" @click="editcreative(record)"></a-button>
                                </span>
                                </a>
                                <!--<template slot="filterList" slot-scope="text,record" href="javascript:;">
                                    <a-popconfirm
                                                 :title="$t('pro.campaigns.filterListMessPage')"
                                                  @confirm="handleFilerList(record)"
                                                  okText="Yes" cancelText="No">
                                        <a href="javascript:;">{{filerList(record)}}
                                            <a-icon type="select" v-if="record.filterListId !== undefined"/>
                                        </a>
                                    </a-popconfirm>
                                </template>-->

                                <!-- 印象 -->
                                <!--<span slot="pixels" slot-scope="text,record" style="min-width: 100px" href="javascript:;">
                                    {{record.pixels | Maximpressions}}
                                </span>-->

                                <!-- 投标 -->
                                <span slot="bids" slot-scope="text,record" style="min-width: 100px" href="javascript:;">
                                {{record.bids | Maximpressions}}
                            </span>

                                <span slot="activateTime" slot-scope="text,record" style="display: flex; min-width: 95px;">
                                <span style="margin: 0 auto">
                                    {{record.activateTime}}
                                </span>
                            </span>
                                <span slot="expireTime" slot-scope="text,record" style="display: flex; min-width: 95px;">
                                <span style="margin: 0 auto">
                                   {{record.expireTime}}
                                </span>
                            </span>

                                <span slot="totalBudget" slot-scope="text,record" href="javascript:;">
                                {{record | CampaignsBudget}}
                            </span>
                                <template slot="wins" slot-scope="text,record" href="javascript:;">
                                    {{record.wins? record.wins:0}}
                                </template>
                                <template slot="winsPrice" slot-scope="text,record" href="javascript:;">
                                    {{record.winsPrice? record.winsPrice.toFixed(2):0}}
                                </template>
                                <template slot="Balance" slot-scope="text,record" href="javascript:;">
                                    {{record | handleBalance}}
                                </template>
                                <a slot="action"  slot-scope="text" href="javascript:;" style="display: block;min-width: 112px;">
                                    <a-button
                                            :title="$t('pro.public.header.Reports')"
                                            type="primary"
                                            shape="circle"
                                            icon="line-chart"
                                            @click="handleDetailReports(text)"
                                            style="margin-right: 5px;"
                                    />
                                    <a-button
                                            :title="$t('pro.campaigns.DupModelOK')"
                                            type="primary"
                                            shape="circle"
                                            icon="copy"
                                            @click="handleCopy(text)"
                                            style="margin-right: 5px;"
                                    />
                                    <a-button
                                            :title="$t('pro.campaigns.Archived')"
                                            type="primary"
                                            shape="circle"
                                            icon="folder"
                                            @click="handleArchived(text)"
                                            style="margin-right: 5px;"
                                    />
                                    <!-- <a-button
                                             :title="$t('pro.campaigns.Archived')"
                                             type="primary"
                                             shape="circle"
                                             icon="eye"
                                             style="margin-right: 5px;"
                                     />-->
                                </a>
                            </a-table>
                        </div>
                  


                    <!--复制广告活动的模态框-->
                    <a-modal
                            :title="$t('pro.campaigns.DupModelOK')"
                            v-model="visibleDup"
                            @ok="handleCopyOk"
                            :okText="$t('pro.campaigns.DupModelOK')"
                            :cancelText="$t('pro.public.buttonClose')"
                            :confirmLoading="confirming"
                            @cancel="handleCopyClose"
                    >
                        <a-table
                                rowKey="name"
                                size="small"
                                :pagination=false
                                bordered
                                :columns="Duplicatecolumns"
                                :dataSource="DuplicateData"
                        >
                            <span slot="name" v-text="DuplicateData[0].name"></span>
                            <a-input type="textarea" slot="newname" v-model="newName">
                            </a-input>
                            <a-checkbox slot="DuplicateCheck" @change="copySon"></a-checkbox>
                        </a-table>
                    </a-modal>
                    <!--归档的模态框-->
                    <a-modal
                            :title="$t('pro.campaigns.Archived')"
                            v-model="visibleArc"
                            @ok="handleArchivedOk"
                            :okText="$t('pro.campaigns.Archived')"
                            :cancelText="$t('pro.public.buttonClose')"
                            :confirmLoading="confirming"
                            @cancel="handleArchivedClose"
                    >
                        <a-card class="Archivedcard"
                                type="inner"
                                :bordered=false>
                            <p><strong v-text="$t('pro.campaigns.ArchivedcardTitle')"></strong></p>
                            <p v-text="$t('pro.campaigns.ArchivedcardContent')"></p>
                        </a-card>
                        <a-table
                            size="small"
                            rowKey="name"
                            :pagination=false
                            bordered
                            :columns="Archivedcolums"
                            :dataSource="ArchivedData"
                        >
                        </a-table>
                    </a-modal>

                   <!-- <a-modal
                            :title="$t('pro.campaigns.DupModelOK')"
                            v-model="true"
                            :okText="$t('pro.campaigns.DupModelOK')"
                            :cancelText="$t('pro.public.buttonClose')"
                            :confirmLoading="confirming"
                            @ok="handleArchivedOk"
                    >
                    </a-modal>-->
                </div>
                <a-pagination
                    v-if="!empty"
                    style="text-align: right;margin-top:1rem;"
                    showSizeChangera
                    showQuickJumper
                    :pageSizeOptions="pageSizeOptions"
                    :pageSize="pagination.size"
                    :total="pagination.total"
                    v-model="pagination.current"
                    @showSizeChange="handleChange"
                    @change="handleChange"
                />
            </div>
        </div>
    </div>
</template>

<script>
    // 用户Campaigns的所有数据列
    // 提取columns的标题用作checkbox设置项
    // 通过plainShadow来寻找该选项在表格中原本的位置，获取columnID通过数组splice方法插入

    import {changeState, getAllDataByPage, copyCampaigns, archivedCampaigns} from "@/api/campaigns";
    import {formatMoney, numberFormat} from "@/utils/tool";
    import {ARCHIVED, ACTIVE, NOTACTIVE} from "@/utils/publicStatus"
    export default {
        mounted() {
            this.handleSelectAll();
            window.addEventListener("resize", this.resize);
            this.isScreen()
        },
        destroyed() {
            window.removeEventListener("resize", this.resize);
        },
        watch:{
            screenWidth(val){
                // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
                if (!this.timer) {
                    // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
                    this.screenWidth = val
                    this.timer = true
                    //打印screenWidth变化的值
                    let that = this
                    if (that.screenWidth <= 375 ){
                        that.columns[that.columns.length-1].fixed = false
                    }else if(that.screenWidth >= 1900){
                        that.columns[that.columns.length-1].fixed = false
                    }else{
                        that.columns[that.columns.length-1].fixed = 'right'
                    }
                    that.timer = false
                }
            },
            islocale(newval) {
                if (newval == 'cn') {
                    this.columns.length = 0
                    this.$t('pro.campaigns.columnsplainOptions').forEach(item =>{
                        this.columns.push(this.$t('pro.campaigns.columnsPlainShadow')[item])
                    });
                } else {
                    this.columns.length = 0
                    this.$t('pro.campaigns.columnsplainOptions').forEach(item =>{
                        this.columns.push(this.$t('pro.campaigns.columnsPlainShadow')[item])
                    });
                }
            }
        },

        data() {
            return {
                ACTIVE,
                NOTACTIVE,
                ARCHIVED,
                pagination: {
                    size: 10,
                    current: 1,
                }, //分页器
                pageSizeOptions: ['5', '10', '20', '30', '40', '50'],  //分页下拉列表
                confirming: false,
                visible: false,
                action: null,
                switchStatus: null,
                empty: false,
                data: [],
                DuplicateData: [{name: ""}],
                ArchivedData: [],
                screenWidth: document.body.clientWidth,
                // 总可显示列
                visibleDup: false,
                visibleArc: false,
                loading: false,
                copyCheck: false,
                copyCampaignId: null,
                newName: '',
                openSetting: false,
                // 表格中显示的内容项：Status,Delivery,ID...，
                // 用户自定义显示的选项内容
                checkedList: [],
                // 总的表格可显示的内容项
                columnsNoChange: true,
                columns: [],
                timer: false,
                campaignsStatus:null,
            };
        },

        filters: {
            //处理最大印象数格式
            Maximpressions(text) {
                return numberFormat(text)
            },
            //处理余额的显示
            handleBalance(record){
                let balance = record.totalBudget - record.winsPrice
                return formatMoney(Number(balance), 2, "$")
            },
            //处理活动预算格式
            CampaignsBudget(record) {
                let budget = formatMoney(Number(record.totalBudget), 2, "$")
                let spend = formatMoney(Number(record.winsPrice), 2, "$")
                return budget+ '/' +spend
            },
            //判断黑白名单
            /*filerList(record) {
                if (record.filterListId !== undefined) {
                    if (record.filterListType == 0) {
                        return this.$t('pro.Editcampaigns.BlackList') + ":\n" + record.filterListName
                    } else if (record.filterListType == 1) {
                        return this.$t('pro.Editcampaigns.WhiteList') + ":\n" + record.filterListName
                    }
                } else {
                    return this.$t('pro.campaigns.none')
                }
            },*/
        },

        computed: {
            plainOptions() {
                return this.$t('pro.campaigns.columnsplainOptions')
            },
            plainShadow() {
                return this.$t('pro.campaigns.columnsPlainShadow')
            },
            Duplicatecolumns() {
                return this.$t('pro.campaigns.Duplicatecolumns')
            },
            Archivedcolums() {
                return this.$t('pro.campaigns.Archivedcolums')
            },
            islocale() {
                return this.$store.state.locale;
            },
            //判断细节状态
            handleDetails(record) {
                return function (record) {
                    if (record.status == ARCHIVED) {
                        return this.$t('pro.campaigns.Archived')
                    } else {
                        if (record.creativeLimit > 0) {
                            if(record.status == ACTIVE) {
                                return this.$t('pro.campaigns.Activated')
                            } else {
                                return this.$t('pro.campaigns.Notactive')
                            }
                        } else {
                            return this.$t('pro.campaigns.Empty')
                        }
                    }
                }
            },
        },
        
        methods: {
            isScreen(){
                let that = this
                if (that.screenWidth <= 375 ){
                    that.columns[that.columns.length-1].fixed = false
                }else if(that.screenWidth >= 1900){
                    that.columns[that.columns.length-1].fixed = false
                }else{
                    that.columns[that.columns.length-1].fixed = 'right'
                }
            },
            resize() {
                this.screenWidth = document.body.clientWidth;
            },
            //改变页数的事件
            handleChange(page, pageSize) {
                this.pagination.size = pageSize
                this.pagination.current = page
                this.fetch()
            },
            //判断是否为归档广告活动，归档广告活动不能进行编辑
            handleEditCampaign(record) {
                this.$router.push({ path: `/bidder/editcampaign/id/` + record.id });
            },
            // 黑白名单过滤器跳转
            /*handleFilerList(record) {
                if (record.filterListId !== undefined) {
                    this.$router.push({
                        path: `/bidder/filterlist/view/id/` + record.filterListId,//跳转到查询过滤器列表页面
                        query: {id: record.filterListId, listName: record.filterListName}
                    })
                } else {
                    this.$message.warning(this.$t('pro.campaigns.filterListWarning'))
                }
            },*/

            viewcreative(record) {
                this.$store.commit("changeCampaigns", record);
                this.$router.push({
                    path: "/bidder/viewcreative/campaignid/" + record.id,
                    query: { campaignsStatus: record.status }
                });
            },
            editcreative(record) {
                this.$store.commit("changeCampaigns", record);
                this.$router.push("/bidder/editcreative/campaignid/" + record.id);
            },
            //改变活动的状态
            statusChange(record) {
                this.loading = true;//开启等待动画
                if (record.status === NOTACTIVE) {
                    record.status = ACTIVE
                } else {
                    record.status = NOTACTIVE
                }
                changeState({
                    ids: record.id,
                    status: record.status
                })
                    .then(res => {
                        if (res.data.code == 200) {
                            this.fetch()
                            this.$message.info(this.$t('pro.campaigns.statusUpdate'));
                        } else {
                            this.fetch()
                        }
                    })
                    .finally(() => {
                        this.loading = false;//关闭动画
                    })
            },
            //筛选全部广告活动
            handleSelectAll() {
                if (this.plainOptions.length == 11) {
                    this.plainOptions.splice(2,0,"3")
                    this.plainOptions.push("13")
                }
                this.fetch()
            },
            //筛选广告活动的状态
            handleSelectActive(status) {
                this.campaignsStatus = status
                this.loading = true
                if (status == ARCHIVED) {
                    if (this.plainOptions.length == 13){
                        this.plainOptions.pop()
                        this.plainOptions.splice(2,1)
                    }
                    this.fetch({type: status})
                } else {
                    if (this.plainOptions.length == 11) {
                        this.plainOptions.splice(2,0,"3")
                        this.plainOptions.push("13")
                    }
                    this.fetch({type: status})
                }
            },
            //表格的发生改变的刷新事件
            handleTableChange(pagination, filters, sorter) {
                this.pagination = pagination;
                this.fetch({
                    sortField: sorter.field,
                    sortOrder: sorter.order,
                    ...filters
                });
            },
            fetch(params = {}) {
                let that = this;
                this.columns.length = 0;
                that.plainOptions.forEach(item =>{
                    that.columns.push(that.plainShadow[item])
                });
                this.empty = false;
                this.loading = true;
                params.page = this.pagination.current || 1;
                params.results = this.pagination.size || 10;
                getAllDataByPage({...params})
                    .then(res => {
                        let {code, data} = res.data || {};
                        if (code == 200) {

                            this.data = data.records || [] ;

                            if (data.records && data.records.length != 0) {
                                this.pagination = data; //每页
                            } else {
                                this.empty = true
                            }
                            this.data.forEach(item =>{
                                item.activateTime = item.activateTime.slice(0,10);
                                item.expireTime = item.expireTime.slice(0,10);
                            });
                        }
                    })
                    .finally(() => {
                        this.loading = false;
                        if (this.data && this.data.length == 0) {
                            this.empty = true
                        }
                    });
            },
            //查看对应活动的报表
            handleDetailReports(text) {
                //跳到对应报表页面
                this.$router.push('/reports/campaigns/'+text.id);
            },
            copySon(e) {
                this.copyCheck = e.target.checked
            },
            // 复制广告活动
            handleCopy(text) {
                this.visibleDup = true
                let name = text.name;
                if (this.DuplicateData.length == 1) {
                    this.DuplicateData[0]['name'] = name
                }
                this.newName = name + '-Copy'
                this.copyCampaignId = text.id
            },
            //确认复制广告活动的事件
            handleCopyOk() {
                this.confirming = !this.confirming;//开启按钮等待动画
                copyCampaigns({
                    id: this.copyCampaignId,
                    copySon: this.copyCheck,
                    copyName: this.newName
                }).then(res => {
                    if (res.data.code == 200) {
                        this.$message.success(this.$t('pro.campaigns.DuplicateSuccess'));
                    }
                    this.getVisible()
                    this.visibleDup = false
                }).catch(err => {
                    this.$message.error(this.$t('pro.campaigns.DuplicateError'));
                    this.getVisible()
                    this.visibleDup = false
                })
            },
            getVisible() {//复制及归档操作结束后的关闭模态框和关闭按钮动画
                this.confirming = !this.confirming;//关闭按钮等待动画
                this.fetch();
            },
            //关闭复制广告活动模态框的事件
            handleCopyClose() {
                this.visibleDup = false
            },
            //将活动存档
            handleArchived(text) {
                this.visibleArc = true//显示归档活动的模态框
                this.ArchivedData.push({'id': text.id, 'name': text.name})
            },
            //确认归档广告活动的事件
            handleArchivedOk() {
                this.confirming = !this.confirming;//开启按钮等待动画
                let archivedId = this.ArchivedData[0].id
                archivedCampaigns({
                    id: archivedId
                }).then(res => {
                    if (res.data.code == 200) {
                        this.$message.success(this.$t('pro.campaigns.archivedSuccess'));
                    }
                    this.getVisible()
                    this.visibleArc = false//关闭归档活动的模态框
                    this.ArchivedData = [];//清空
                }).catch(err => {
                    this.$message.error(this.$t('pro.campaigns.archivedError'));
                    this.getVisible()
                    this.visibleArc = false//关闭归档活动的模态框
                    this.ArchivedData = [];//清空
                })
            },
            //取消归档广告活动的事件
            handleArchivedClose() {
                this.visibleArc = false//隐藏归档活动的模态框
                this.ArchivedData = [];//清空
            },
            //搜索广告活动
            onSearch(value) {
                this.fetch({vague: value})
            },
            onChange(value) {
                console.log("changed", value);
            },

            checkboxChange(checkedValues) {
                console.log("checked = ", checkedValues);
            },
            handleClick(e) {
                console.log("click ", e);
            },
            onOpenChange(openKeys) {
                this.openSetting = !this.openSetting;
            },
            saveCheckbox() {
                if (!this.columnsNoChange) {
                    this.plainOptions.length = 0
                    let arr = this.checkedList.sort((a,b)=>{
                        return a-b
                    })
                    arr.forEach(item =>{
                        this.plainOptions.push(item)
                    })
                    if (arr.length <= 9){
                        this.columns[this.columns.length-1].fixed = false
                    } else {
                        this.columns[this.columns.length-1].fixed = 'right'
                    }
                    this.fetch();
                    this.onOpenChange();
                }
            },
            checkedChange(value) {
                this.checkedList = value;
                this.columnsNoChange = false;
            }
        },
    };
</script>


<style lang="less" scoped>
    .Archivedcard {
        color: #856404;
        background-color: #fff3cd;
        border: 1px solid transparent;
        border-color: #ffeeba;
        border-radius: 5px;
        margin-bottom: 10px;
    }

    h1,
    h3 {
        margin-bottom: 0;
    }

    .grid {
        grid-template-columns: repeat(5, auto);
    }
    grid-r{
        grid-template-columns: repeat(1, auto);
    }

    @media screen and (max-width: 768px) {
        .tools.flex-between {
            display: block;
            > div:not(:last-child) {
                margin-bottom: 10px;
            }
            .tools-l {
                grid-template-columns: repeat(3, 1fr);
                > *:nth-child(1) {
                    grid-column: 1;
                    grid-row: 1;
                }
                > *:nth-child(2) {
                    grid-column: 2;
                    grid-row: 1;
                }
                > *:nth-child(3) {
                    grid-column: 3;
                    grid-row: 1;
                }
                > *:nth-child(4) {
                    grid-column: 1 / 4;
                    grid-row: 2;
                }
            }
        }
    }

    @media screen and (max-width: 500px) {
        .tools.flex-between {
            .tools-l {
                grid-template-columns: repeat(2, 1fr);
                > *:nth-child(1) {
                    grid-column: 1;
                    grid-row: 1;
                }
                > *:nth-child(2) {
                    grid-column: 2;
                    grid-row: 1;
                }
                > *:nth-child(3) {
                    grid-column: 1;
                    grid-row: 2;
                }
                > *:nth-child(4) {
                    grid-column: 2;
                    grid-row: 2;
                }
            }
        }
    }

    @media screen and (max-width: 320px) {
        .portlet {
            padding: 12px 15px 15px;
        }
    }

    .ant-checkbox-wrapper:first-child {
        margin-left: 8px;
    }


</style>
